from flask import Flask, render_template, request

def parse_operator(input_str):
    # 处理纯数字自动补加+
    if input_str.strip().isdigit():
        return f'+{input_str.strip()}'
    
    # 去除空格并验证运算符格式
    cleaned = input_str.strip()
    if cleaned and cleaned[0] in '+-*/' and len(cleaned) > 1:
        return cleaned
    return '+'  # 默认值


def find_valid_combinations(A, B, C, steps):
    valid_combinations = set()
    total_steps = len(steps)
    for combo in range(2 ** total_steps):
        current_B, current_C = A, A
        enabled_steps = []
        for i in range(total_steps):
            if (combo >> i) & 1:
                try:
                    current_B = eval(f"current_B {steps[i][0]}")
                    current_C = eval(f"current_C {steps[i][1]}")
                except:
                    break
                enabled_steps.append(f"B:{steps[i][0]}, C:{steps[i][1]}")
        if current_B == B and current_C == C and enabled_steps:
            valid_combinations.add(tuple(enabled_steps))
    return [list(combo) for combo in valid_combinations]


app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        A = int(request.form['A'])
        B = int(request.form['B'])
        C = int(request.form['C'])
        
        steps = []
        for i in range(8):
            raw_op = request.form.get(f'b_op_{i}', '')
            b_op = parse_operator(raw_op)
            raw_op = request.form.get(f'c_op_{i}', '')
            c_op = parse_operator(raw_op)
            steps.append((b_op, c_op))
        
        results = find_valid_combinations(A, B, C, steps)
        return render_template('index.html', results=results, form_data=request.form)
    
    return render_template('index.html', form_data=request.form)

if __name__ == '__main__':
    app.run()